package com.jiayuge.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiayuge.server.common.entity.RespBean;
import com.jiayuge.server.pojo.Menu;
import com.jiayuge.server.pojo.MenuRole;
import com.jiayuge.server.pojo.Role;
import com.jiayuge.server.service.IMenuRoleService;
import com.jiayuge.server.service.IMenuService;
import com.jiayuge.server.service.IRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 功能: 权限组 角色功能的实现
 *
 * @Program: yeb
 * @Date: 2021-11-23 10:06
 * @Author Jiayu.Yang
 */
@RestController
@Api(tags = "PermissionController 权限组")
@RequestMapping("/system/basic/permission")
public class PermissionController {
    @Autowired
    private IRoleService roleService;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private IMenuRoleService menuRoleService;

    @ApiOperation(value = "获取所有的角色")
    @GetMapping("/")
    public List<Role> getAllRole(){
        return roleService.list();
    }

    @ApiOperation(value = "添加角色")
    @PostMapping("/")
    public RespBean addRole(@RequestBody Role role){
        return roleService.addRole(role);
    }

    @ApiOperation(value = "修改角色")
    @PutMapping("/")
    public RespBean updateRole(@RequestBody Role role){
        if (roleService.updateById(role)){
            return RespBean.success("修改成功");
        }
        return RespBean.error("修改失败");
    }

    @ApiOperation(value = "单个删除角色")
    @DeleteMapping("/{id}")
    public RespBean deleteRoleById(@PathVariable Integer id){
        if (roleService.removeById(id)) {
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }

    @ApiOperation(value = "批量删除角色")
    @DeleteMapping("/")
    public RespBean deleteRoleByIds(Integer[] ids){
        if (roleService.removeByIds(Arrays.asList(ids))) {
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }

    @ApiOperation(value = "查询所有菜单")
    @GetMapping("/menus")
    public List<Menu> getAllMenu(){
       return menuService.getAllMenu();
    }

    @ApiOperation(value = "根据角色id查询菜单id")
    @GetMapping("/mid/{rid}")
    public List<Integer> getMidByRid(@PathVariable Integer rid){
        return menuRoleService.list(new QueryWrapper<MenuRole>().eq("rid",rid))
                .stream()
                .map(MenuRole::getMid)
                .collect(Collectors.toList());
    }

    @ApiOperation(value = "更新角色菜单")
    @PutMapping("/roleMenu")
    public RespBean updateMenuRole(Integer rid,Integer[] mids){
        return menuRoleService.updateMenuRole(rid,mids);
    }
}
